package com.lzq.framework.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * @author 2019/6/5 15:39 by 刘赵强
 **/
@Slf4j
public class HttpClientUtil {
    /**
     * get请求
     * @param url 请求URL
     * @param param 请求参数
     * @return url返回值
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = null;
        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            httpclient = HttpClients.createDefault();
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info("请求结果={}",resultString);
            }else{
                log.error("httpclient请求返回状态{}=",response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("httpclient请求异常,可能超时",e);
        } finally {
            try {
                if(httpclient!=null) {
                    httpclient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("资源关闭异常");
            }
        }
        return resultString;
    }
}
